package com.lin.order.controller;

import com.lin.order.entity.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private RestTemplate restTemplate;

    /**
     * 使用spring提供的DiscoverClient工具类可以获取服务的元数据
     * @param id
     * @return
     */

    @Autowired
    private DiscoveryClient discoveryClient;

    /**
     * 基于ribbon的方式调用远程微服务
     * @param id
     * @return
     */
    @RequestMapping(value = "/buy/{id}",method = RequestMethod.GET)
    public Product findById(@PathVariable Long id) {
        Product product =null;
        product = restTemplate.getForObject("http://service-product/product/2", Product.class);
        return product;
    }

    /*@RequestMapping(value = "/buy/{id}",method = RequestMethod.GET)
    public Product findById(@PathVariable Long id) {
        List<ServiceInstance> instances = discoveryClient.getInstances("SERVICE-PRODUCT");
        //获取唯一的一个元数据
        ServiceInstance instance = instances.get(0);
        //根据元数据中的主机ip地址和端口号
        Product product =null;
        product = restTemplate.getForObject("http://"+instance.getHost()+":"+instance.getPort()+"/product/2", Product.class);
        return product;
    }*/
}
